package com.tenglong.teacher.ui.publish;


import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.cuotibao.zhuoxiao.basics.BaseFragment;
import com.cuotibao.zhuoxiao.basics.utils.clean.DataCleanManager;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.requestInfo.HomeworkCorrectInfo;
import com.tenglong.teacher.ui.publish.text.DoodleOnTouchGestureListener;
import com.tenglong.teacher.ui.publish.text.DoodleStoreText;
import com.tenglong.teacher.ui.publish.text.MyDoodleText;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;


import java.util.List;

import cn.forward.androids.utils.ImageUtils;
import cn.hzw.doodle.DoodlePen;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleColor;
import cn.hzw.doodle.core.IDoodleItem;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodlePen;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;

import static cn.hzw.doodle.DoodleView.MAX_SCALE;
import static cn.hzw.doodle.DoodleView.MIN_SCALE;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeworkCorrectingFragment extends BaseFragment implements HomeworkFragmentCallback {

    public static final String KEY_IMAGE_INFO = HomeworkCorrectingFragment.class.getSimpleName() + "key_image_info";

    /**
     * 图片是否准备就绪
     */
    private boolean isDownLoadImageSucceed = false;
    /**
     * DoodleView是否创建成功
     */
    private boolean isCreateDoodleView = false;

    /**
     * 动作监听对象是否就绪
     */
    private boolean isCreateGestureListener = false;

    /**
     * 参数是否就绪
     */
    private boolean isCreateViewAndParam = false;

    /**
     * 涂鸦图片保存监听者
     */
    private SaveListener listener;

    /**
     * 涂鸦动作监听者
     */
    private DoodleOnTouchGestureListener mTouchGestureListener;

    /**
     * 参数对象
     */
    private HomeworkCorrectInfo imageInfo;

    /**
     * 涂鸦平台
     */
    private MyDoodleView mDoodleView;

    /**
     * 图片加载动画显示控件
     */
    private ImageView centerIv;

    /**
     * 图片加载动画
     */
    private ObjectAnimator objectAnimator;

    /**
     * 需要涂鸦的图片
     */
    private Bitmap mBitmap;

    /**
     * 图片显示的最大高度
     */
    private int h;

    /**
     * 图片显示最大宽度
     */
    private int w;

    /**
     * 承载图片涂鸦平台的控件
     */
    private ViewGroup parentView;

    /**
     * 是否显示图片加载失败图标
     */
    private boolean isShowErrorTip = true;

    public HomeworkCorrectingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (mContext instanceof HomeworkActiviCallback) {
            HomeworkActiviCallback callback = (HomeworkActiviCallback) mContext;
            h = callback.getMySelfDisplayAreaHeight();
            w = callback.getMySelfDisplayAreaWidth();
        }
    }

    public static HomeworkCorrectingFragment getInstance(HomeworkCorrectInfo info) {
        HomeworkCorrectingFragment f = new HomeworkCorrectingFragment();
        Bundle param = new Bundle();
        param.putSerializable(KEY_IMAGE_INFO, info);
        f.setArguments(param);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_homework_correcting, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        centerIv = view.findViewById(R.id.centerIv);
        parentView = rootView.findViewById(R.id.doodle_container);
        imageInfo = (HomeworkCorrectInfo) getArguments().getSerializable(KEY_IMAGE_INFO);
        if (imageInfo != null) {
            isCreateViewAndParam = true;
            if (imageInfo.position == 0) {
                createSourceBitmap();
            }
        } else {
            isCreateViewAndParam = false;
        }
    }

    /**
     * 创建bitmap
     */
    private void createSourceBitmap() {
        showLoadingAnimation();
        RequestOptions options = GlideOptions.getGlideRequestOptions()
                .override(w == 0 ? Target.SIZE_ORIGINAL : w, h == 0 ? Target.SIZE_ORIGINAL : h)
                .fitCenter();
        Log.e("createSourceBitmap", imageInfo.currentUrl == null ? "" : imageInfo.currentUrl);
        Glide.with(this).load(imageInfo.currentUrl == null ? "" : imageInfo.currentUrl).
                apply(options).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                if (mBitmap != null) {
                    mBitmap.recycle();
                    mBitmap = null;
                }
                hideLoadingAnimation();
                mBitmap = ((BitmapDrawable) resource).getBitmap();
                if (mBitmap == null) {
                    isDownLoadImageSucceed = false;
                    return;
                }
                isDownLoadImageSucceed = true;
                createDoodleView();
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                hideLoadingAnimation();
                if (isShowErrorTip) {
                    showErrorLoading();
                } else {
                    releaseResource();
                    isShowErrorTip = false;
                }
                isDownLoadImageSucceed = false;
            }
        });
    }

    /**
     * 创建图片涂鸦平台，并装载
     */
    @SuppressLint("ClickableViewAccessibility")
    private void createDoodleView() {
        if (mDoodleView != null) {
            parentView.removeAllViews();
            imageInfo.errorNum = 0;
            imageInfo.errors.clear();
            imageInfo.scrawlPath = "";
            mDoodleView.clear();
            if (mContext != null && (mContext instanceof HomeworkActiviCallback)) {
                HomeworkActiviCallback callback = ((HomeworkActiviCallback) mContext);
                callback.setClearGreenViewState();
            }
            mDoodleView = null;
        }
        if (mTouchGestureListener != null) {
            mTouchGestureListener = null;
        }
        mDoodleView = new MyDoodleView(mContext, mBitmap, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap doodleBitmap, Runnable callback) {
                Tiny.FileCompressOptions compressOptions = new Tiny.FileCompressOptions();
                compressOptions.isKeepSampling = true;
                compressOptions.size = 100;
                compressOptions.quality = 100;
                compressOptions.compressDirectory = DataCleanManager.getCorrectHomeworkLink(mContext);
                Tiny.getInstance().source(doodleBitmap).asFile().withOptions(compressOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile, Throwable t) {
                        if (!isSuccess) {
                            listener.onFailure();
                            return;
                        }
                        ImageUtils.addImage(mContext.getContentResolver(), outfile);
                        imageInfo.scrawlPath = outfile;
                        listener.onSaveSucceed();
                    }
                });
            }

            @Override
            public void onReady(IDoodle doodle) {
                isCreateDoodleView = true;
            }
        }, null);

        mDoodleView.setMyTouchEventListener(new MyDoodleView.MyTouchEventListener() {
            private boolean isDown = false;
            private boolean isMove = false;

            @Override
            public void touchEvent(MotionEvent event) {
                if (mDoodleView != null && mDoodleView.getPen() == DoodlePen.BRUSH) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        isDown = true;
                    } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                        isMove = true;
                    } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                        if (isDown || isMove) {
                            isMove = false;
                            isDown = false;
                            if (mContext != null && (mContext instanceof HomeworkActiviCallback)) {
                                HomeworkActiviCallback callback = ((HomeworkActiviCallback) mContext);
                                callback.setClearGreenViewState();
                            }
                        }
                    }
                }
            }
        });

        mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {
                if (selected && getSelectType() == SelectType.DELETE) {
                    if (selectableItem instanceof MyDoodleBitmap) {
                        if (((MyDoodleBitmap) selectableItem).getSelectType() == SelectType.ERROR) {
                            List<IDoodleItem> doodleItems = mDoodleView.getAllItem();
                            if (doodleItems != null && doodleItems.size() > 0) {
                                for (IDoodleItem doodleItem : doodleItems) {
                                    if ((doodleItem instanceof MyDoodleText) && ((MyDoodleText) doodleItem).getErrorBitmap() != null &&
                                            ((MyDoodleText) doodleItem).getErrorBitmap() == selectableItem) {
                                        mDoodleView.removeItem(doodleItem);
                                    }
                                }
                            }
                            if (imageInfo != null) {
                                imageInfo.errors.remove(selectableItem);
                            }
                        }
                    } else if (selectableItem instanceof MyDoodleText) {
                        IDoodleItem errorBitmap = ((MyDoodleText) selectableItem).getErrorBitmap();
                        if (errorBitmap != null) {
                            List<IDoodleItem> doodleItems = mDoodleView.getAllItem();
                            if (doodleItems != null && doodleItems.size() > 0) {
                                for (IDoodleItem doodleItem : doodleItems) {
                                    if (doodleItem instanceof MyDoodleText) {
                                        IDoodleItem errorItem = ((MyDoodleText) doodleItem).getErrorBitmap();
                                        if (errorItem != null && errorItem == errorBitmap && doodleItem != selectableItem) {
                                            mDoodleView.removeItem(doodleItem);
                                        }
                                    }
                                }
                            }
                            if (imageInfo != null) {
                                imageInfo.errors.remove(errorBitmap);
                            }
                            mDoodleView.removeItem(errorBitmap);
                        }
                    }
                    mDoodleView.removeItem(selectableItem);
                    mTouchGestureListener.setSelectedItem(null);
                }

                if (mContext != null && (mContext instanceof HomeworkActiviCallback)) {
                    HomeworkActiviCallback callback = ((HomeworkActiviCallback) mContext);
                    callback.setClearGreenViewState();
                }
            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle,IDoodleSelectableItem selectableItem, float x, float y) {
                if (mContext != null && (mContext instanceof HomeworkActiviCallback)) {
                    HomeworkActiviCallback callback = ((HomeworkActiviCallback) mContext);
                    if (doodle.getPen() == DoodlePen.TEXT) {
                        if(selectableItem!=null && selectableItem instanceof DoodleStoreText && selectableItem.contains(x,y)){
                            callback.createDoodleText(mDoodleView, mTouchGestureListener, (DoodleStoreText) selectableItem, x, y);
                        }else{
                            callback.createDoodleText(mDoodleView, mTouchGestureListener, null, x, y);
                        }
                    } else if (doodle.getPen() == DoodlePen.BITMAP) {
                        callback.createDoodleBitmap(mDoodleView, mTouchGestureListener, null, x, y);
                    }
                    callback.setClearGreenViewState();
                }
            }
        });

        IDoodleTouchDetector detector = new DoodleTouchDetector(mContext, mTouchGestureListener);
        mDoodleView.setDoodleMinScale(MIN_SCALE);
        mDoodleView.setDoodleMaxScale(MAX_SCALE);
        mDoodleView.setDefaultTouchDetector(detector);
        parentView.addView(mDoodleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        isCreateGestureListener = mTouchGestureListener != null;
        // Setting parameters.设置参数
        if (mContext != null && mContext instanceof HomeworkActiviCallback) {
            ((HomeworkActiviCallback) mContext).synchronousState();
        }
    }

    /**
     * 显示图片加载动画
     */
    private void showLoadingAnimation() {
        centerIv.setVisibility(View.VISIBLE);
        centerIv.setImageResource(R.drawable.loading);
        if (objectAnimator == null) {
            objectAnimator = ObjectAnimator.ofFloat(centerIv, "rotation", 0f, 360f);
            objectAnimator.setDuration(2000);
            objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                objectAnimator.setAutoCancel(true);
            }
        }
        objectAnimator.start();
    }

    /**
     * 隐藏图片加载动画
     */
    private void hideLoadingAnimation() {
        releaseResource();
        centerIv.setVisibility(View.GONE);
    }

    /**
     * 显示图片加载失败图标
     */
    private void showErrorLoading() {
        centerIv.setVisibility(View.VISIBLE);
        releaseResource();
        centerIv.setImageResource(R.drawable.load_error);
    }

    /**
     * 释放图片加载动画资源
     */
    private void releaseResource() {
        if (objectAnimator != null) {
            objectAnimator.cancel();
        }
        if (centerIv.getAnimation() != null) {
            centerIv.getAnimation().cancel();
        }
    }

    @Override
    public void onDestroy() {
        releaseResource();
        super.onDestroy();
        listener = null;
    }

    /**
     * 获取当前所属状态
     *
     * @return
     */
    private SelectType getSelectType() {
        return ((HomeworkActiviCallback) mContext).getSelectType();
    }

    /**
     * 获取图片涂鸦平台对象
     *
     * @return
     */
    @Override
    public DoodleView getContainerView() {
        return mDoodleView;
    }

    /**
     * 获取图片涂鸦动作监听者对象
     *
     * @return
     */
    @Override
    public DoodleOnTouchGestureListener onDoodleOnTouchGesture() {
        return mTouchGestureListener;
    }

    /**
     * 获取所需涂鸦图片对象是否创建成功
     *
     * @return
     */
    @Override
    public boolean isDownLoadImageSucceed() {
        return isDownLoadImageSucceed;
    }

    /**
     * 获取图片涂鸦界面是否创建成功状态
     *
     * @return
     */
    @Override
    public boolean isCreateDoodleView() {
        return isCreateDoodleView;
    }

    /**
     * 获取图片涂鸦动作监听者是否创建成功状态
     *
     * @return
     */
    @Override
    public boolean isCreateGestureListener() {
        return isCreateGestureListener;
    }

    /**
     * 获取当前fragment位置
     *
     * @return
     */
    @Override
    public int getFragmentPosition() {
        if (imageInfo != null) {
            return imageInfo.position;
        } else
            return 0;
    }

    /**
     * 暂停图片加载
     */
    @Override
    public void stopLoadBitmap() {
        Glide.with(this).pauseRequests();
    }

    /**
     * 恢复图片加载
     */
    @Override
    public void resumeLoadBitmap() {
        Glide.with(this).resumeRequests();
    }

    /**
     * 判断此界面是否涂鸦
     *
     * @return
     */
    @Override
    public boolean isScrawl() {
        if (mDoodleView != null) {
            return mDoodleView.getAllItem() != null && mDoodleView.getAllItem().size() > 0;
        }
        return false;
    }

    /**
     * 刷新图片（强制）
     */
    @Override
    public void refreshBitmap() {
        if (isAdded() && isCreateViewAndParam) {
            isShowErrorTip = false;
            createSourceBitmap();
        }
    }

    /**
     * 刷新图片（在满足条件的情况下）
     */
    @Override
    public void reLoadBitmap() {
        if (isAdded() && !isDownLoadImageSucceed && isCreateViewAndParam && !isCreateDoodleView && !isCreateGestureListener) {
            createSourceBitmap();
        }
    }

    /**
     * 设置图片保存监听者
     *
     * @param listener
     */
    public void setListener(SaveListener listener) {
        this.listener = listener;
    }

    public interface SaveListener {
        void onSaveSucceed();

        void onFailure();
    }
}
